import { reqGetUserInfo, reqLogin } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { constantRoutes, resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken() || '', // 逻辑运算符
    userInfo: {},
    routes: constantRoutes
  },
  mutations: {
    setToken(state, payload) {
      state.token = payload
      setToken(payload) // 设置token
    },
    setInfo(state, payload) {
      state.userInfo = payload
    },
    // 点击退出
    logout(state) {
      state.token = ''
      removeToken()
      state.userInfo = {}
      // 重置路由
      resetRouter()
      // 重置路由规则
      state.routes = constantRoutes
    },
    // 路由管理。变成，响应式的
    addFilterRoutes(state, paylod) {
      // state.routes.push(...paylod)
      state.routes = [...constantRoutes, ...paylod]
    }
  },
  actions: {
    async login(ctx, payload) {
      // console.log(11)
      const res = await reqLogin(payload)
      // console.log(res)
      ctx.commit('setToken', res.data)
    },
    // 获取用户信息
    async getInfo(ctx) {
      const { data } = await reqGetUserInfo()
      ctx.commit('setInfo', data)
      return data
    }
  }
}
